package com.example.ihs.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ihs.common.result.Result;
import com.example.ihs.entity.User;
import com.example.ihs.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author universe
 * @since 2024-03-31
 */
@RestController
@RequestMapping("/ihs/user")
public class UserController {

        @Autowired
        private UserService userService;


        @ApiOperation(value = "用户登录")
        @PostMapping("/login")
        public Result get(@RequestBody User user) {
            //查询用户是否存在
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, user.getUsername());
            User userSelectOne = userService.getOne(wrapper);
            //验证密码
            String userPassword = user.getPassword();
            if (userSelectOne.getPassword().equals(userPassword)) {
                return Result.ok("允许登录");
            }
            //登录失败
            return Result.fail();
        }

        @ApiOperation(value = "根据id查询一条用户")
        @GetMapping("selectById/{id}")
        public Result save(@PathVariable Integer id) {
            User userServiceById = userService.getById(id);
            return Result.ok(userServiceById);
        }

        @ApiOperation(value = "新增用户")
        @PostMapping("save")
        public Result save(@RequestBody User user, MultipartFile multipartFile) {
            String username = user.getUsername();
            int count = userService.count(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
            if (count!=0){
                return Result.fail("该用户已经存在");
            }
            //头像上传
            String fileAvatar = userService.uploadFileAvatar(multipartFile);
            user.setAvatarUrl(fileAvatar);
            userService.save(user);
            return Result.ok();
        }

        @ApiOperation(value = "修改用户")
        @PutMapping("update")
        public Result updateById(@RequestBody User user) {
            userService.updateById(user);
            return Result.ok();
        }

        @ApiOperation(value = "删除用户")
        @DeleteMapping("remove/{id}")
        public Result remove(@PathVariable Long id) {
            userService.removeById(id);
            return Result.ok();
        }

    }




